if(typeof(Storage)!=="undefined" && postAction == 'create'){
    $("#Post_content").val(localStorage.post_content);
}  

tinyMceConfig.setup = function(ed) {
    ed.on('keyup', function(e) {
        postSave();
    });
}
tinymce.init(tinyMceConfig);



$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#post-form').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: post_upload_url,
        autoUpload: true,
        previewMaxWidth: 120,
        previewMaxHeight: 90,

        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp)$/i,
        //acceptFileTypesError: "Chỉ hỗ trợ .gif .jpg. png .bmp",
        maxFileSize: 10240000, // 10 MB
        //maxFileSizeError: "Ảnh phải &le; 10 MB",
        minFileSize: undefined, // No minimal file size
        maxNumberOfFiles: 20,

    });
//    $('#post-form').bind('fileuploaddestroy', function (e, data) { $('#ajax-loading').fadeIn('fast'); });
//    $('#post-form').bind('fileuploaddestroyed', function (e, data) { $('#ajax-loading').fadeOut('fast'); });
    $('button.delete').live('click', function(){
        var row = $(this).parent().parent();
        row.fadeOut('fast');
    })
    
    // Load existing files: 
    $('#post-form').addClass('fileupload-processing');
    $.ajax({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: $('#post-form').fileupload('option', 'url'),
        dataType: 'json',
        context: $('#post-form')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done').call(this, $.Event('done'), {result: result});
    });
         
    // set is_cover to cookie
    $('input[name="is_cover"]').live('click', function(){
        $.cookie('post_img_cover', $(this).val(), { path: '/' });    
    });

    $('.add_to_content').live('click', function(e){
        e.preventDefault();
        tinyMCE.execCommand('mceInsertRawHTML',false, '<img src="' + $(this).attr('url') + '" />');
    });


    $("#upload-grid").mCustomScrollbar({
        scrollInertia:300,
        horizontalScroll:false,
        advanced:{
            updateOnBrowserResize:true, /*update scrollbars on browser resize (for layouts based on percentages): boolean*/
            updateOnContentResize:true, /*auto-update scrollbars on content resize (for dynamic content): boolean*/
            autoExpandHorizontalScroll:false, /*auto-expand width for horizontal scrolling: boolean*/
            autoScrollOnFocus:true, /*auto-scroll on focused elements: boolean*/
            normalizeMouseWheelDelta:false /*normalize mouse-wheel delta (-1/1)*/
        },
        scrollButtons:{
            enable:true
        },
        theme:"dark-thick"
    });
    
    
    // load map
    if($('#Post_latlng').val() != ''){
        google_map($('#Post_latlng').val()); 
    }
    else if($('#Post_city_id').val() != ''){
        $('#Post_city_id').change();    
    }

});



    

// cat select
var catTypeBefore;
var typeBefore;

$("#Post_cat_id").focus(function(){
    catTypeBefore = $('option:selected', this).attr('type');
    typeBefore = $('#Post_type').val();
})
.change(function() {

    var catTypeChange = $('option:selected', this).attr('type');
    $('.block-toggle').fadeOut('fast');   

    switch(catTypeChange){
        case 'SALE':
            $('#Post_type option[value$="thue"]').remove();
            $('#block-type').fadeIn('fast');
            $('#block-state').fadeIn('fast');
            //                $('#block-area').fadeIn('fast');
            $('#block-price').fadeIn('fast');
            $('#block-address').fadeIn('fast');
            break;
        case 'SERVICE':
            //                $('#block-type').fadeIn('fast');
            //                $('#block-state').fadeIn('fast');
            //                $('#block-area').fadeIn('fast');
            $('#block-price').fadeIn('fast');
            $('#block-address').fadeIn('fast');
            break;
        case 'IMMOVABLE':
//            console.log(catTypeBefore);
//            console.log(catTypeChange);
            if(catTypeBefore != undefined && catTypeBefore != catTypeChange){
                $('#Post_type').html('<option value=""></option>'+
                    '<option value="mua" '+(typeBefore == 'mua' ? 'selected="selected"' : '')+'>Mua</option>'+
                    '<option value="ban" '+(typeBefore == 'ban' ? 'selected="selected"' : '')+'>Bán</option>'+
                    '<option value="thue">Thuê</option>'+
                    '<option value="cho-thue">Cho thuê</option>');
                
            }
            $('#block-type').fadeIn('fast');
            //                $('#block-state').fadeIn('fast');
            $('#block-area-use, #block-area-floor').fadeIn('fast');
            $('#block-price').fadeIn('fast');
            $('#block-address').fadeIn('fast');
            break;
        case 'ARTICLE':
            //                $('#block-type').fadeIn('fast');
            //                $('#block-state').fadeIn('fast');
            //                $('#block-area').fadeIn('fast');
            //                $('#block-price').fadeIn('fast');
            //                $('#block-address').fadeIn('fast');
            break;
    }   

}).change();



$("#Post_city_id").change(function(){
    var city_id = $(this).val();
    $("#Post_district_id").html('<option value=""></option>');
    $.each(districtDataGroupByCityId[city_id], function(key, value){
        $("#Post_district_id").append('<option value="'+key+'">'+value+'</option>');
    });

    write_address_full();    

    google_map(citiesRefID[city_id].latlng);
    $('#Post_latlng').val(citiesRefID[city_id].latlng);
});

$("#Post_district_id").change(function(){
    if($(this).val() != ''){
        var latlng = districtsRefID[$(this).val()].latlng != '' ? districtsRefID[$(this).val()].latlng : citiesRefID[city_id].latlng;
        google_map(latlng);
        $('#Post_latlng').val(latlng);
        $("#Post_address").focus();
    }    
    write_address_full();
});

$("#Post_address").bind('change keyup blur focus', function(){
    write_address_full();
});


$('#post-form').submit(function(){

    $('#Post_content').val(tinyMCE.activeEditor.getContent());
    // remove values of fields not need
    switch($('#Post_cat_id option:selected').attr('type')){
        case 'SALE':
            $('#Post_area_use, Post_area_floor').val('');
            break;
        case 'SERVICE':
            $('#Post_area_use, Post_area_floor, #Post_type, #Post_state').val('');
            break;
        case 'IMMOVABLE':
            $('#Post_state').val('');
            break;
        case 'ARTICLE':
            $('#Post_area_use, Post_area_floor, #Post_type, #Post_state, #Post_price, #Post_address').val('');
            break;
    }
});

function postAfterValidate(form, data, hasError){
    if(hasError){
        var focusSelector;
        $.each(data, function(key, value){ 
            focusSelector = '#'+key;
            $.each(value, function(i, msg){
                myGrowl(msg, 'error');
            });        
        });
        $(focusSelector).focus();
        scrollToAnchor(focusSelector);    
        return false;
        
    }else{
        $('#ajax-loading').fadeIn();
        var msg = ($('#post-form').attr('actionType') == 'create' ? 'Bài của bạn đang được tải lên.'
        : 'Bài của bạn đang được cập nhật.')+' Xin vui lòng chờ trong giây lát.';
        myGrowl(msg, 'info');
        return true;
    }
}

function google_map(latlng) {
    var latlng = latlng.split(",");
    var lat = latlng[0];
    var lng = latlng[1];

    var center_position = new google.maps.LatLng(lat, lng);
    var marker_position = new google.maps.LatLng(lat, lng);
    var marker;
    var map;

    var mapOptions = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: center_position,

        panControl: false,
        mapTypeControl: false,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        streetViewControl: false,
        scaleControl: false,
        rotateControl: false,
        overviewMapControl: false
    };

    map = new google.maps.Map(document.getElementById('map'), mapOptions);

    marker = new google.maps.Marker({
        map:map,
        draggable:true,
        animation: google.maps.Animation.DROP,
        position: marker_position,
        icon : new google.maps.MarkerImage('/files/img/red_flag.png',
            new google.maps.Size(69,48),
            new google.maps.Point(0,0),
            new google.maps.Point(35,48)
        )
    }); 
    google.maps.event.addListener(marker, 'click', function(){
        if (marker.getAnimation() != null) {
            marker.setAnimation(null);
        } else {
            marker.setAnimation(google.maps.Animation.BOUNCE);
        }
    });

    google.maps.event.addListener(marker, 'dragend', function(){
        var loc = marker.getPosition();
        var lat = roundNumber(loc.lat(),6);
        var lng = roundNumber(loc.lng(),6);
        $('#Post_latlng').val(lat+','+lng).change();
    });

    google.maps.event.trigger(map, 'resize');
    map.setZoom(map.getZoom());
    //        map.fitBounds(bounds);
}



function write_address_full(){
    var city =       $("#Post_city_id option:selected").text();
    var district =   $("#Post_district_id option:selected").text();
    var address =   $("#Post_address").val();
    var array = new Array(); 
    if(address != '') array.push(address);
    if(district != '') array.push(district);
    if(city != '') array.push(city);
    var addressFull = array.join(', ');
    $('#address_full').text(addressFull);

}
write_address_full();

// save all fields to cookie
function postSave(){
    if(postAction != 'create') return;
    
    var post = new Object();
    post.cat_id = $('#Post_cat_id').val();
    post.type = $('#Post_type').val();
    post.state = $('#Post_state').val();
    post.price = $('#Post_price').val();
    post.price = $('#Post_price').val();
    post.area_use = $('#Post_area_use').val();
    post.area_floor = $('#Post_area_floor').val();
    post.title = $('#Post_title').val();
    post.cover = $('.image_cover:checked').val();
    post.city_id = $('#Post_city_id').val();
    post.district_id = $('#Post_district_id').val();
    post.address = $('#Post_address').val();
    post.latlng = $('#Post_latlng').val();
    post.show_map = $('#Post_show_map').is(':checked')
    post.is_all_city = $('#Post_is_all_city').is(':checked')

    $.cookie('post_saved', JSON.stringify(post), {path: '/'});
    
    // save content to localStorage    
    if(typeof(Storage)!=="undefined"){
        if(tinyMCE.activeEditor !== null){
            localStorage.post_content = tinyMCE.activeEditor.getContent(); 
        }
    }
}

$('#post-form').change(function(){
    postSave();
});